//
//  TKNetworkManager+Extension.swift
//  TKWBOne
//
//  Created by tiankun on 16/8/31.
//  Copyright © 2016年 1. All rights reserved.
//

import Foundation

extension TKNetworkManager {

    func statusList(since_id: Int64 = 0, max_id: Int64 = 0,completion: (list: [[String : AnyObject]]?, isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        let parameters = ["since_id" : "\(since_id)","max_id" : "\(max_id > 0 ? max_id - 1 : 0)"]
        tokenRequest(URLString: urlString, parameters: parameters) { (json, isSuccess) in
            let result = json?["statuses"] as? [[String : AnyObject]]
            completion(list: result, isSuccess: isSuccess)
        }
    }
    func unreadCount(completion: (count: Int)->()) {
        guard let uid = userAccount.uid else
        {
            return
        }
        let urlString = "https://rm.api.weibo.com/2/remind/unread_count.json"
        let parameters = ["uid" : uid]
        tokenRequest(URLString: urlString, parameters: parameters) { (json, isSuccess) in
            let dict = json as? [String : AnyObject]
            let count = dict?["status"] as? Int
            completion(count: count ?? 0)
        }
    }
}
// MARK: OAuth相关方法
extension TKNetworkManager {
    func loadAccessToken(code: String, completion:(isSuccess: Bool)->()) {
        let urlString = "https://api.weibo.com/oauth2/access_token"
        let parameters = ["client_id" : TKAppKey,
                          "client_secret" : TKAPPSecret,
                          "grant_type": "authorization_code",
                          "code" : code,
                          "redirect_uri" : TKRedirectURI]
        request(method: .POST, URLSrting: urlString, parameters: parameters) { (json, isSuccess) in
            self.userAccount.yy_modelSet(with: (json as? [String : AnyObject]) ?? [:])
            print("\(self.userAccount)")
            //保存模型
            self.userAccount.saveAccount()
            //完成回调
            completion(isSuccess: isSuccess)
        }
    }
}
